package com.softeem.score.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softeem.score.common.exception.MyException;
import com.softeem.score.manager.mapper.StudentMapper;
import com.softeem.score.manager.mapper.SysUserMapper;
import com.softeem.score.manager.service.StudentService;
import com.softeem.score.manager.service.SysUserService;
import com.softeem.score.model.dto.StudentDto;
import com.softeem.score.model.entity.school.Student;
import com.softeem.score.model.entity.system.SysUser;
import com.softeem.score.model.vo.common.ResultCodeEnum;
import com.softeem.score.model.vo.school.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2024-02-14
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageInfo<StudentVo> findByPage(StudentDto studentDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);// 开启分页
        List<StudentVo> students = studentMapper.findByPage(studentDto);// 查询数据
        PageInfo<StudentVo> pageInfo = new PageInfo(students);// 封装分页数据
        return pageInfo;
    }

    @Transactional
    @Override
    public void deleteByStudentNumber(String studentNumber) {
        sysUserMapper.deleteSysUserBySysUserName(studentNumber);
        studentMapper.deleteByStudentNumber(studentNumber);

    }

    @Transactional
    @Override
    public void deleteStudents(List<Long> studentIds) {
        for (Long studentId : studentIds) {
            Student student = studentMapper.findById(studentId);
            sysUserMapper.deleteSysUserBySysUserName(student.getStudentNumber());
        }
        studentMapper.deleteStudents(studentIds);
    }

    @Transactional
    @Override
    public void updateStudent(Student student) {
        Student oldStudent =  studentMapper.findById(student.getId());
        if (!oldStudent.getContactInformation().equals(student.getContactInformation())){
            sysUserMapper.updateMobile(student.getStudentNumber(), student.getContactInformation());
        }
        studentMapper.updateStudent(student);
    }


    @Transactional
    @Override
    public void saveStudent(Student student) {
        if (studentMapper.findStudentIdsByStudentNumber(student.getStudentNumber()) > 0) {
            throw new MyException(ResultCodeEnum.STUDENTNUMBER_EXISTS_NOTINSERTED);
        } else {
            studentMapper.saveStudent(student);
            // 设置用户名为学生学号
            String username = student.getStudentNumber();
            // 获取身份证后6位作为密码
            String idCardLastSixDigits = student.getIdCard().substring(student.getIdCard().length() - 6);
            // 对密码进行加密
            String encryptedPassword = DigestUtils.md5DigestAsHex(idCardLastSixDigits.getBytes(StandardCharsets.UTF_8));
            // 判断联系方式是否为手机号或邮箱
            String contactInfo = student.getContactInformation();
            String mobile = null;
            String email = null;
            if (isValidPhoneNumber(contactInfo)) {
                mobile = contactInfo;
            } else if (isValidEmail(contactInfo)) {
                email = contactInfo;
            }
            // 创建 SysUser 对象并保存到数据库
            SysUser sysUser = new SysUser(username, encryptedPassword, mobile, email, null, 0, null, null);
            sysUserService.saveSysUser(sysUser);
            sysUserMapper.bindingRoles(sysUser.getId(), 2L);
        }

    }

    // 判断是否为有效手机号
    private boolean isValidPhoneNumber(String contactInfo) {
        // 定义手机号的正则表达式
        String phoneRegex = "^1[3-9]\\d{9}$";
        // 判断联系方式是否符合手机号格式
        return contactInfo.matches(phoneRegex);
    }

    // 判断是否为有效邮箱
    private boolean isValidEmail(String contactInfo) {
        // 定义邮箱的正则表达式
        String emailRegex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
        // 判断联系方式是否符合邮箱格式
        return contactInfo.matches(emailRegex);
    }
}
